<template>
    <div>
        <div class="im-header displayFlex justifyCtBwt flex-algin-center"
            v-if="storeMsg && Object.keys(storeMsg).length > 0">
            <span class="iconfont icon-arrows_left back-icon" @click="toBackUrl()"></span>
            <p class="im-header-title flex1"><span class="positionR im--header-ctitle">
                    <span>{{storeMsg.name}}</span>
                    <span class="title-mark" v-if="scene == 'team'">商家</span></span>
            </p>
            <span></span>
        </div>
        <div class="box" v-resize="scrollBottom" ref="scrllBottom">
            <div class="chat-content" @click="closeBottomBox">
                <div v-for="(value,chatMsgListKey) in chatMsgList">
                    <p v-if="chatMsgListKey == 0" class="chat-time">{{getTime(value.time,"yy年MM月dd日 hh:mm:ss")}}</p>
                    <p v-else-if="chatMsgListKey != 0 && value.time - 300000 > chatMsgList[chatMsgListKey-1].time"
                        class="chat-time">{{getTime(value.time,"yy年MM月dd日 hh:mm:ss")}}</p>
                    <!--客服-->
                    <div class="chat-avatar displayFlex" v-if="!value.avatar">
                        <img class="im-chat-userheader" v-if="storeMsg" :src="storeMsg.logo" alt="">
                        <div class="flex1">
                            <div class="im-chat-name" v-if="storeMsg" @click="openHKHWConfirm('好看好玩支持实时评价客服')">
                                {{$route.query.customerType ? '客服' : storeMsg.name}}
                                <span v-if="scene == 'team'">
                                    <!--这里不需要显示客服以前的星级,因为接口里面只有最新一条的评论-->
                                    <img v-for="value in 5" class="star-icon"
                                        src="../../assets/images/im/white_star_icon.png" alt="">
                                </span>
                                <span class="commont-score-text" v-if="scene == 'team'">点击进行评分</span>
                            </div>
                            <!--（0文本消息 1图片 2语音 3视频 4地理位置 5红包 6转账)-->
                            <div class="im-chat-content">
                                <!--文字-->
                                <div v-if="value.content.messageType == 0" v-html="faceReplace(value.content.text)">
                                </div>
                                <!--图片-->
                                <img @click="bigImg($event)" v-else-if="value.content.messageType == 1"
                                    class="width-full" :src="value.content.mediaUrl" alt="">
                                <!--语音-->
                                <audio v-else-if="value.content.messageType == 2" class="im-audio-style" controls
                                    :src="value.content.mediaUrl"></audio>
                                <!--视屏video-->
                                <div class="video positionR" v-else-if="value.content.messageType == 3"
                                    @click="playVideo($event)">
                                    <video x5-video-player-type="h5" video-player-type="h5" class="im-video-style"
                                        :src="value.content.mediaUrl"></video>
                                    <img class="video-icon" id="videoBtn"
                                        :src="staticImageUrl('images/video_play_btn.png')" alt="" />
                                </div>
                                <!--地理位置-->
                                <div v-else-if="value.content.messageType == 4" @click="toHaoKanHaoWan()">
                                    对方发送了一条定位信息，您需要打开【好看好玩】进行查看，点击打开
                                </div>
                                <!--红包-->
                                <div v-else-if="value.content.messageType == 5" @click="toHaoKanHaoWan()">
                                    收到红包，您需要打开【好看好玩】进行领取，点击打开
                                </div>
                                <!--转账-->
                                <div v-else-if="value.content.messageType == 6" @click="toHaoKanHaoWan()">
                                    收到一笔转账，您需要打开【好看好玩】进行收取，点击打开
                                </div>
                            </div>
                        </div>
                    </div>
                    <!--TODO 判断是否为店长-->
                    <div class="positionR displayFlex flexCenter mt-24" v-if="false">
                        <div class="store-leader-line"></div>
                        <span class="store-leader-content displayFlex flexCenter">
                            <img class="store-leader-icon" src="../../assets/images/im/store_leader.png" alt="">
                            <span class="store-leader-text">店长已接入</span>
                        </span>
                    </div>
                    <!--用户-->
                    <div class="chat-receiver displayFlex" v-if="value.avatar">
                        <div class="im-chat-content">
                            <!--（0文本消息 1图片 2语音 3视频 4地理位置 5红包 6转账)-->
                            <!--发送文件暂时不考虑-->
                            <span v-if="value.content.messageType == 0" v-html="faceReplace(value.content.text)"></span>
                            <img @click="bigImg($event)" class="width-full" v-else-if="value.content.messageType == 1"
                                :src="value.content.mediaUrl" alt="">
                            <audio v-else-if="value.content.messageType == 2" controls
                                :src="value.content.mediaUrl"></audio>
                            <div class="video positionR" v-else-if="value.content.messageType == 3"
                                @click="playVideo($event)">
                                <video x5-video-player-type="h5" video-player-type="h5" class="im-video-style"
                                    :src="value.content.mediaUrl"></video>
                                <img class="video-icon" :src="staticImageUrl('images/video_play_btn.png')" alt="" />
                            </div>
                        </div>
                    </div>
                </div>
                <!--调出键盘的时候整个要跟着调出来-->
                <div style="height:1.2rem;"></div>
                <div v-if="showPics || showFace" class="key-bord"></div>
            </div>
        </div>
        <div id='wrapMsg' style="width: 100%;height: 1px;"></div>
        <!--@keydown="msgTextContent($event)"
                 @mousedown="msgTextContent($event)"
                 @blur="msgTextContent($event)"
                 @focus="msgTextContent($event)"-->
        <div class="input-wrap">
            <div class="positionR">
                <div contenteditable=true type="text" ref="msgText" id='msgText' class='im-chat-textarea'
                    @blur="msgTextContent($event,{type:'iosBlur'})" @focus="msgTextContent($event,{type:'iosFocus'})"
                    @input="msgTextContent($event)" rows=1 cols=40>
                </div>
                <label for="msgText">
                    <span class="msg-text-placeholder" v-if="!showSendBtn">请输入消息...</span>
                </label>
            </div>
            <div class="im-chat-input-wicon displayFlex justifyCtArd mt-15">
                <label for="btn_camera">
                    <img class="im-chat-input-icon" src="../../assets/images/im/im_camera_icon.png" alt="">
                    <input class="camera-input" mutiple="mutiple" name="btn_camera" id="btn_camera" type="file"
                        accept="image/*" capture="camera" @change="sendImg($event)" />
                </label>
                <img @click="tapFace('face')" class="im-chat-input-icon" src="../../assets/images/im/smile_icon.png"
                    alt="">
                <!--TODO 在线接待的功能兼容性差，暂时注释-->
                <img v-if="false" @click="shouVideoIm" class="im-chat-input-icon"
                    src="../../assets/images/im/videoCall.png" alt="">
                <img @click="tapFace('pic')" v-if="!showSendBtn" class="im-chat-input-icon"
                    src="../../assets/images/im/add_icon.png" alt="">
                <button v-else class="send-msg" @click="sendNWMsg">发送</button>
            </div>
            <div class="face-box" v-if="showFace">
                <img class="face-icon" @click="addFace($event,key)" v-for="(value,key) in emojiList.emoji"
                    :src="imgPath + 'images/emoji/emoji/' + value.file" alt="">
            </div>
            <div v-if="showPics" class="face-box photos displayFlex justifyCtArd">
                <div class="photos-wrap">
                    <label for="btn_phones">
                        <img src="../../assets/images/im/photos.png" alt="">
                        <p>相机</p>
                    </label>
                    <input class="camera-input" multiple id="btn_phones" type="file" accept="image/*"
                        @change="sendImg($event)" />
                </div>
            </div>
        </div>
        <v-ImVideo v-if="nim && Object.keys(nim).length > 0" ref="ImVideo" :getNim="nim" v-show="videoIm"
            :chatGroupId='chatGroupId'>
        </v-ImVideo>
        <v-loading v-if="loading"></v-loading>
    </div>
</template>
<script>
import MD5 from "js-md5";
import SDK from '../../assets/js/im/NIM_Web_SDK_v7.5.0';
import ImVideo from './ImVideo';
import Vue from 'vue';
import XCookie from "../../x/XCookie";
import { mapMutations } from 'vuex'

export default {
    name: "ImChat",
    data () {
        return {
            sessionId: '', //聊天id，用来清除聊天记录
            textArea: "",//输入框内容
            chatGroupId: '',//聊天室id
            scene: '',
            showFace: false,//表情显示
            showPics: false,//图片相机等的显示
            imInfo: '',//im内部的基本信息
            emojiList: '',//表情
            nim: {},//网易云信
            loading: false,//loading
            subjectType: -1,//入口主题类型 0(商品);1(订单);2(活动);-1(其他);
            subjectName: '消息',//入口主题名称
            storeMsg: {},//店铺信息
            lastTextMsg: '',//记录上一条文字信息
            imContentHeight: 0,
            storeId: null,//店铺id
            showSendBtn: false,//解决ios低版本输入框闪烁的问题
            account: '',//自己的账号
            chatMsgList: [
                // {
                //     time:'0',
                //     avatar:true,//是否为本人发出的信息
                //     name:'',//用户/客服名字，
                //     userheader:'',//用户或者商家的头衔
                //     content:{
                //         text:'111',//文字、表情
                //         messageType:0,//消息类型（0文本消息 1图片 2语音 3视频 4地理位置 5红包 6转账)
                //         mediaUrl:'',//图片语音等地址
                //     }
                // }
            ]
        }
    },
    created () {
        //未登录状态去登录
        if (!this.userId && !this.thirdId) {
            this.toLogin();
            return;
        }
        this.subjectType = this.$route.query.subjectType || this.subjectType;
        this.subjectName = this.$route.query.subjectName || this.subjectName;
        this.storeId = this.$route.query.storeId || this.storeId;
        this.chatGroupId = this.$route.query.chatGroupId || this.chatGroupId;
        this.scene = this.$route.query.scene || this.scene;
        let that = this;
        this.$nextTick(() => {
            that.init();
        })
    },

    computed: {
        // 视频弹窗的的显示
        videoIm () {
            return this.$store.state.logic.videoImHidden;
        },
        sessionList () {
            return this.$store.state.logic.sessionList;
        },
        currentThird () {
            return this.$store.getters.currentThirdFn
        },
        currentThirdId () {
            let currentThird = this.$store.getters.currentThirdFn;
            if (currentThird && currentThird.thirdId) {
                return currentThird.thirdId;
            }
            return 0;
        },
        currentUser () {
            return this.$store.getters.currentUserFn
        },
        hintList () {
            return this.$store.state.logic.hintList
        }
    },
    directives: {
        resize: {
            update: function (el, binding, vnode) { //3-更新
                let width = '', height = '';
                let that = this;

                function get () {
                    const style = document.defaultView.getComputedStyle(el);
                    if (width !== style.width || height !== style.height) {
                        binding.value({ width, height });
                    }
                    width = style.width;
                    height = style.height;
                }

                el.__vueReize__ = setInterval(get, 200);
            },
            unbind: function (el, binding, vnode) { //5-解绑
                clearInterval(el.__vueReize__);
            }
        },
    },
    mounted () {
        // setTimeout(() => {

        //     console.log(this.chatGroupId,'chatGroupId8888888');
        // }, 3000);

        /*这个是解决ios中页面初始化之后无法获取手机输入框焦点的bug*/
        if (this.isIphone) {
            this.iosBlur()
        }
        let that = this;
        /*兼容ios下输入框被遮挡的问题*/
        $("#msgText").on('focus', function () {
            let i = 0;
            let height = document.body.scrollHeight;
            let timer = setInterval(function () {
                if (i <= 10) {
                    document.body.scrollTop = height;
                    i++
                } else {
                    clearInterval(timer);
                }
            }, 10)
        })
        /*兼容安卓下页面被输入框遮挡的问题*/
        window.onresize = function (e) {

            that.scrollBottom();
            var h = $(window).height();
            if (that.isAndroid) {
                if (h <= window.screen.availHeight / 2) {
                    $('#wrapMsg')[0].scrollIntoView();
                }
            }
        }
    },
    // 离开页面的操作
    destroyed: function () {
        this.nim.resetSessionUnread(this.sessionId)
        // this.stopTimer();
    },
    methods: {
        ...mapMutations(['createNeplayerRoom']),
        shouVideoIm () {
            this.$refs.ImVideo.videoCall()
            this.$store.commit('videoImHidden', { show: true })
        },
        // 获取聊天用户信息
        getUserInfo () {
            if (JSON.stringify(this.sessionList) == '[]' && sessionStorage.getItem('storeInfo')) {
                this.storeMsg = JSON.parse(sessionStorage.getItem('storeInfo'))
                return
            }
            this.sessionList.forEach(userInfo => {
                if (userInfo.to == this.chatGroupId) {
                    this.storeMsg = {
                        name: userInfo.datas.groupName,
                        logo: userInfo.datas.photo,
                        from: userInfo.from
                    }
                    sessionStorage.setItem('storeInfo', JSON.stringify(this.storeMsg))
                }
            });

        },
        init () {
            // imgPath
            this.initNim();
            if (this.storeId) {
                this.getStoreMsg();
            } else {
                this.getUserInfo()
            }
        },
        //初始化NIM 信息
        initNim () {
            let that = this;
            /*chatAccount4UserPwd —— MD5Utils.md5Encrypt(consumerChatAccount + "ybt").toUpperCase());*/
            let appKey = this.isOnline ? '0acabe4c61bb55009c9c11f055e7eb8c' : 'ba3506c42c732dc7c5a52642fab360a1';
            let account = that.$store.state.currentUser.chatAccount || (that.currentThird && that.currentThird.chatAccount ? that.currentThird.chatAccount : '');
            that.account = account;
            let password = MD5(account + 'ybt').toUpperCase();
            // this.nim = SDK.NIM.getInstance({
            //     appKey: appKey,//appkey
            //     account: account,//账号
            //     token: password,//密码
            //     onconnect: ()=>{
            //       alert('连接成功')
            //         if(that.chatGroupId){
            //             that.getImChatRecord();
            //         }

            //     },//连接成功
            //     onwillreconnect: ()=>{console.log("onwillreconnect")},//即将重连
            //     ondisconnect: ()=>{console.log("ondisconnect 22")},//连接失败
            //     onerror: ()=>{console.log("onerror")},//出错
            //     onDisconnect: ()=>{console.log("onDisconnectD")},//
            //     onmsg: that.onMsg,//接收消息
            // });

            this.nim = this.$store.state.logic.groupChat.nim
            if (!this.nim || !this.nim.account) {
                this.createNeplayerRoom({ connentSuccess });
            } else {
                connentSuccess();
            }
            async function connentSuccess () {
                that.nim = that.$store.state.logic.groupChat.nim

                // if( !(that.chatMsgList && that.chatMsgList.length > 0)){
                //     that.getImChatRecord()
                // }
                //获取聊天室id(这里是群组)；
                if (that.storeId) {
                    let params = {
                        storeId: that.storeId,
                        userId: that.userId,
                        thirdId: that.thirdId,
                        enterType: '0',
                        enterTypeKey: '0',
                    }
                    await that.$store.dispatch('getChatGroupIdApi', params).then((data) => {
                        if (data.success) {
                            that.chatGroupId = data.result;
                            that.alreadyRead();
                            // if (that.nim && that.nim.account) {
                            //     that.getImChatRecord();
                            // }
                        } else {
                            that.$root.$emit("创建聊天失败，请刷新页面");
                        }
                    })
                }
                if (that.chatGroupId) {
                    that.getImChatRecord()
                }
            }
            //表情包
            this.emojiList = {
                "emoji": {
                    "[大笑]": { file: "emoji_0.png" },
                    "[可爱]": { file: "emoji_01.png" },
                    "[色]": { file: "emoji_02.png" },
                    "[嘘]": { file: "emoji_03.png" },
                    "[亲]": { file: "emoji_04.png" },
                    "[呆]": { file: "emoji_05.png" },
                    "[口水]": { file: "emoji_06.png" },
                    "[汗]": { file: "emoji_145.png" },
                    "[呲牙]": { file: "emoji_07.png" },
                    "[鬼脸]": { file: "emoji_08.png" },
                    "[害羞]": { file: "emoji_09.png" },
                    "[偷笑]": { file: "emoji_10.png" },
                    "[调皮]": { file: "emoji_11.png" },
                    "[可怜]": { file: "emoji_12.png" },
                    "[敲]": { file: "emoji_13.png" },
                    "[惊讶]": { file: "emoji_14.png" },
                    "[流感]": { file: "emoji_15.png" },
                    "[委屈]": { file: "emoji_16.png" },
                    "[流泪]": { file: "emoji_17.png" },
                    "[嚎哭]": { file: "emoji_18.png" },
                    "[惊恐]": { file: "emoji_19.png" },
                    "[怒]": { file: "emoji_20.png" },
                    "[酷]": { file: "emoji_21.png" },
                    "[不说]": { file: "emoji_22.png" },
                    "[鄙视]": { file: "emoji_23.png" },
                    "[阿弥陀佛]": { file: "emoji_24.png" },
                    "[奸笑]": { file: "emoji_25.png" },
                    "[睡着]": { file: "emoji_26.png" },
                    "[口罩]": { file: "emoji_27.png" },
                    "[努力]": { file: "emoji_28.png" },
                    "[抠鼻孔]": { file: "emoji_29.png" },
                    "[疑问]": { file: "emoji_30.png" },
                    "[怒骂]": { file: "emoji_31.png" },
                    "[晕]": { file: "emoji_32.png" },
                    "[呕吐]": { file: "emoji_33.png" },
                    "[拜一拜]": { file: "emoji_160.png" },
                    "[惊喜]": { file: "emoji_161.png" },
                    "[流汗]": { file: "emoji_162.png" },
                    "[卖萌]": { file: "emoji_163.png" },
                    "[默契眨眼]": { file: "emoji_164.png" },
                    "[烧香拜佛]": { file: "emoji_165.png" },
                    "[晚安]": { file: "emoji_166.png" },
                    "[强]": { file: "emoji_34.png" },
                    "[弱]": { file: "emoji_35.png" },
                    "[OK]": { file: "emoji_36.png" },
                    "[拳头]": { file: "emoji_37.png" },
                    "[胜利]": { file: "emoji_38.png" },
                    "[鼓掌]": { file: "emoji_39.png" },
                    "[握手]": { file: "emoji_200.png" },
                    "[发怒]": { file: "emoji_40.png" },
                    "[骷髅]": { file: "emoji_41.png" },
                    "[便便]": { file: "emoji_42.png" },
                    "[火]": { file: "emoji_43.png" },
                    "[溜]": { file: "emoji_44.png" },
                    "[爱心]": { file: "emoji_45.png" },
                    "[心碎]": { file: "emoji_46.png" },
                    "[钟情]": { file: "emoji_47.png" },
                    "[唇]": { file: "emoji_48.png" },
                    "[戒指]": { file: "emoji_49.png" },
                    "[钻石]": { file: "emoji_50.png" },
                    "[太阳]": { file: "emoji_51.png" },
                    "[有时晴]": { file: "emoji_52.png" },
                    "[多云]": { file: "emoji_53.png" },
                    "[雷]": { file: "emoji_54.png" },
                    "[雨]": { file: "emoji_55.png" },
                    "[雪花]": { file: "emoji_56.png" },
                    "[爱人]": { file: "emoji_57.png" },
                    "[帽子]": { file: "emoji_58.png" },
                    "[皇冠]": { file: "emoji_59.png" },
                    "[篮球]": { file: "emoji_60.png" },
                    "[足球]": { file: "emoji_61.png" },
                    "[垒球]": { file: "emoji_62.png" },
                    "[网球]": { file: "emoji_63.png" },
                    "[台球]": { file: "emoji_64.png" },
                    "[咖啡]": { file: "emoji_65.png" },
                    "[啤酒]": { file: "emoji_66.png" },
                    "[干杯]": { file: "emoji_67.png" },
                    "[柠檬汁]": { file: "emoji_68.png" },
                    "[餐具]": { file: "emoji_69.png" },
                    "[汉堡]": { file: "emoji_70.png" },
                    "[鸡腿]": { file: "emoji_71.png" },
                    "[面条]": { file: "emoji_72.png" },
                    "[冰淇淋]": { file: "emoji_73.png" },
                    "[沙冰]": { file: "emoji_74.png" },
                    "[生日蛋糕]": { file: "emoji_75.png" },
                    "[蛋糕]": { file: "emoji_76.png" },
                    "[糖果]": { file: "emoji_77.png" },
                    "[葡萄]": { file: "emoji_78.png" },
                    "[西瓜]": { file: "emoji_79.png" },
                    "[光碟]": { file: "emoji_80.png" },
                    "[手机]": { file: "emoji_81.png" },
                    "[电话]": { file: "emoji_82.png" },
                    "[电视]": { file: "emoji_83.png" },
                    "[声音开启]": { file: "emoji_84.png" },
                    "[声音关闭]": { file: "emoji_85.png" },
                    "[铃铛]": { file: "emoji_86.png" },
                    "[锁头]": { file: "emoji_87.png" },
                    "[放大镜]": { file: "emoji_88.png" },
                    "[灯泡]": { file: "emoji_89.png" },
                    "[锤头]": { file: "emoji_90.png" },
                    "[烟]": { file: "emoji_91.png" },
                    "[炸弹]": { file: "emoji_92.png" },
                    "[枪]": { file: "emoji_93.png" },
                    "[刀]": { file: "emoji_94.png" },
                    "[药]": { file: "emoji_95.png" },
                    "[打针]": { file: "emoji_96.png" },
                    "[钱袋]": { file: "emoji_97.png" },
                    "[钞票]": { file: "emoji_98.png" },
                    "[银行卡]": { file: "emoji_99.png" },
                    "[手柄]": { file: "emoji_100.png" },
                    "[麻将]": { file: "emoji_101.png" },
                    "[调色板]": { file: "emoji_102.png" },
                    "[电影]": { file: "emoji_103.png" },
                    "[麦克风]": { file: "emoji_104.png" },
                    "[耳机]": { file: "emoji_105.png" },
                    "[音乐]": { file: "emoji_106.png" },
                    "[吉他]": { file: "emoji_107.png" },
                    "[火箭]": { file: "emoji_108.png" },
                    "[飞机]": { file: "emoji_109.png" },
                    "[火车]": { file: "emoji_110.png" },
                    "[公交]": { file: "emoji_111.png" },
                    "[轿车]": { file: "emoji_112.png" },
                    "[出租车]": { file: "emoji_113.png" },
                    "[警车]": { file: "emoji_114.png" },
                    "[自行车]": { file: "emoji_115.png" }
                }
            };
            /*获取本地聊天记录，如果用云信的历史记录就不用自己再获取了，但是要存储，因为还有页面需要*/
            // this.getChatRecord();

        },
        /*获取店铺信息*/
        getStoreMsg () {
            let params = {
                storeId: this.storeId,
                userId: this.userId,
                thirdId: this.thirdId || 0
            }
            this.$store.dispatch('getStoreMsgApi', params).then((data) => {
                if (data.success) {
                    this.storeMsg = data.result;
                } else if (data.errMsg) {
                    this.$root.$emit("toast", { msg: data.errMsg });
                } else {
                    this.$root.$emit("toast", { msg: "获取商家信息失败,请刷新页面" });
                }
            })
        },
        playVideo (e) {
            $(e.currentTarget).find('video').removeAttr('x5-video-player-type');
            $(e.currentTarget).find('video').removeAttr('video-player-type');
            $(e.currentTarget).find('video')[0].play();
        },

        msgTextContent (e, obj) {
            //对表情的处理
            this.textArea = e.currentTarget.innerHTML;
            if (obj && obj.type && obj.type == 'iosBlur') {
                this.iosBlur(0, this.imContentHeight)
            } else if (obj && obj.type && obj.type == 'iosFocus') {
                this.closeBottomBox()
            }
        },

        /*发送消息*/
        sendNWMsg () {
            let that = this;
            //发送之前
            if ($('#msgText img').length > 0 && $('#msgText img').hasClass('face-icon')) {
                $('#msgText img').each(function () {
                    let _this = this;
                    if ($(_this).attr('faceIcon')) {
                        var faceIcon = $(_this).attr('faceIcon')
                        let spanNode = `<span>${faceIcon}</span>`
                        $(spanNode).insertBefore($(_this));
                        $(_this).remove();
                    }
                });
                that.textArea = $('#msgText').html();
                that.textArea = that.textArea.replace(/<span>|<\/span>/ig, '');
            } else {
                that.textArea = $('#msgText').html();
            }
            that.textArea = that.textArea.replace(/<div>|<\/div>/ig, '');
            that.textArea = that.textArea.replace(/\&nbsp;|<br>|<br\/>/ig, ' ');
            /*向网易云发信息*/
            let customObj = {
                "customerServiceMsg": true,
                "senderType": that.userId ? 1 : 7,
                "senderKey": that.userId ? that.userId : this.thirdId
            };
            that.msg = that.nim.sendText({
                scene: that.scene,
                to: that.chatGroupId,
                text: that.textArea,
                custom: JSON.stringify(customObj),
                done: that.sendMsgDone,
            });

        },
        /*发送img*/
        sendImg (event, mediaType) {
            let that = this;
            var getFile = new FileReader();
            /*文件*/
            var thisFile = event.currentTarget.files[0];
            let type = '';
            let typeStatus = 1;
            if (mediaType == 'video') {
                typeStatus = 3;
            } else if (mediaType == 'image') {
                typeStatus = 1;
            }
            //消息类型（0文本消息 1图片 2语音 3视频 4地理位置 5红包 6转账)
            /*h5无法直接调用录音所以这里不需要弄audio*/
            if (thisFile.type.indexOf('image') != -1) {
                type = 'image';
            } else if (thisFile.type.indexOf('video') != -1) {
                type = 'video';
            } else {
                type = 'file';
            }
            let customObj = {
                "customerServiceMsg": true,
                "senderType": that.userId ? 1 : 7,
                "senderKey": that.userId ? that.userId : that.thirdId
            };
            that.nim.sendFile({
                scene: that.scene,
                to: that.chatGroupId,
                type: type,
                custom: JSON.stringify(customObj),
                fileInput: event.currentTarget,
                beginupload: function (upload) {
                    // - 如果开发者传入 fileInput, 在此回调之前不能修改 fileInput
                    // - 在此回调之后可以取消图片上传, 此回调会接收一个参数 `upload`, 调用 `upload.abort();` 来取消文件上传
                },
                uploadprogress: function (obj) {
                    that.loading = true;
                },
                uploaddone: function (error, file, msg) {
                    if (error) {
                        that.loading = false;
                        return;
                    }
                },
                beforesend: function (msg) {
                },
                done: (error, msg) => {
                    that.loading = false;
                    //消息类型（0文本消息 1图片 2语音 3视频 4地理位置 5红包 6转账)
                    //不考虑文件以及其他的
                    if (thisFile.type.indexOf('image') != -1) {
                        typeStatus = 1;
                    } else if (thisFile.type.indexOf('audio') != -1) {
                        typeStatus = 2;
                    } else if (thisFile.type.indexOf('video') != -1) {
                        typeStatus = 3;
                    }
                    if (error) {
                        that.$root.$emit('toast', { 'msg': "上传失败" })
                    }
                    let obj = {
                        content: '',
                        messageType: typeStatus,
                        medioUrl: msg.file.url,
                    }
                    that.sendServerAndPage(msg, obj)
                }
            });
        },
        sendVideo () {

        },
        /*接收消息*/
        onMsg (msg) {
            let that = this;
            let messageType = 0;
            let medioUrl = ''
            if (msg.type.indexOf('image') != -1) {
                messageType = 1;
                medioUrl = msg.file.url;
            } else if (msg.type.indexOf('audio') != -1) {
                messageType = 2;
                medioUrl = msg.file.url;
            } else if (msg.type.indexOf('video') != -1) {
                messageType = 3;
                medioUrl = msg.file.url;
            } else if (msg.type.indexOf('text') != -1) {
                msg.text = this.faceReplace(msg.text);
            }
            let tempObj = {
                type: msg.type,
                content: msg.text,
                messageType: messageType,
                medioUrl: medioUrl,
                time: msg.time,
                isReceive: true,//是否为接收消息
            }
            this.sendToPage(tempObj);
            /*TODO 这里需要调取后台接口去实现是否已读设置*/
            this.alreadyRead()
        },
        /*已读*/
        alreadyRead () {
            /*标记为是否已读*/
            let that = this;
            let params = {
                chatGroupId: that.chatGroupId,
                userId: that.userId,
                thirdId: that.thirdId,
            }
            this.$store.dispatch('alreadyReadApi', params).then((data) => {
                console.log(data);
            })
        },
        /*发送消息之后的回调*/
        sendMsgDone (error, msg) {
            let typeStatus = 0
            if (!error || (msg && msg.from)) {
                this.sendServerAndPage(msg);
            }
        },
        sendServerAndPage (imMsg, obj) {
            /*向本地服务器中发送消息记录*/
            let that = this;
            // let url = `${this.NW_API_API_LOCALE_VERSION}/customer/order/message/user/add`;
            let medioUrl = obj && obj.medioUrl ? obj.medioUrl : '';
            let messageType = obj && obj.messageType ? obj.messageType : 0;
            let content = messageType == 0 ? that.textArea : '';
            let paramas = {
                "chatGroupId": this.chatGroupId,       //---------云信聊天群组ID
                "messageId": imMsg.idClient,             //---------云信消息ID
                "userId": that.userId,           //---------用户ID
                "messageType": messageType,                //---------消息类型（0文本消息 1图片 2语音 3视频 4地理位置 5红包 6转账)
                "content": content,        // ---------发送文本消息时的内容(消息类型为0时传)
                "subjectType": that.subjectType,               //---------入口主题类型 0(商品);1(订单);2(活动);-1(其他);
                "subjectName": that.subjectName,       //---------入口主题名称
                "thirdId": that.thirdId,       //---------第三方id
                "customerType": this.$route.query.customerType,
                "customerKey": this.$route.query.customerKey,
            };
            if (that.scene !== 'p2p') {
                this.$store.dispatch('sendServerAndPageApi', paramas).then((data) => {
                    console.log(data, 'data')
                })
            }
            let time = Date.parse(new Date());
            let tempObj = {
                content,
                messageType,
                medioUrl,
                time,
                isReceive: false,
            };
            this.sendToPage(tempObj);
        },
        sendToPage (msg) {
            let that = this;

            let tempObj = {
                time: msg.time,
                avatar: !msg.isReceive,
                userheader: that.$store.state.currentUser.photoUrl || '',//用户或者商家的头衔
                name: that.$store.state.currentUser.userName || '',//用户/客服名字，
                content: {
                    text: msg.content,
                    messageType: msg.messageType,//消息类型（0文本消息 1图片 2语音 3视频 4地理位置 5红包 6转账)
                    mediaUrl: msg.medioUrl,
                },
            };
            if (msg.type != "custom") {
                this.chatMsgList.push(tempObj);
            }
            /*本地存储聊天记录*/
            // this.saveChatRecord(tempObj);
            /*清空输入框内容*/
            if (!msg.isReceive) {
                this.$refs.msgText.innerHTML = '';
                this.textArea = '';
            }
        },
        /*关闭底部box*/
        closeBottomBox () {
            this.showFace = false;
            this.showPics = false;
        },
        // faceReplace(msg){
        //     let that = this;
        //     if( /\[.*\]/.test(msg) ){
        //         for( let value in that.emojiList.emoji){
        //             if( msg.includes(value) ){
        //                 var reg = new RegExp(value.slice(1,-1));
        //                 msg = msg.replace(reg,`<img class="face-icon" style="width: .25rem;height: .25rem;"  src="${this.imgPath}images/emoji/emoji/${that.emojiList.emoji[value].file}" />`);
        //                 msg = msg.replace(/\[|\]/ig,'')
        //             }
        //         }
        //     }
        //     return msg
        // },
        /*TODO 多个表情无法发送，只能发一个*/
        faceReplace (msg) {
            let that = this;
            let tempMsgString = msg
            if (/\[.*?\]/.test(msg)) {
                let msgMatch = msg.match(/\[.*?\]/g);
                msgMatch.forEach((msgMatchValue, index) => {
                    for (let value in that.emojiList.emoji) {
                        if (msgMatchValue == value) {
                            var reg = new RegExp(value.slice(1, -1));
                            msg = msg.replace(reg, `<img class="face-icon" style="width: .25rem;height: .25rem;"  src="${this.imgPath}images/emoji/emoji/${that.emojiList.emoji[value].file}" />`);
                            msg = msg.replace(/\[|\]/ig, '')
                        }
                    }
                })
            }
            return msg
        },
        /*放大图片*/
        bigImg (e) {
            let img = e.currentTarget.className;
            if (img.includes('big-img')) {
                e.currentTarget.className = e.currentTarget.className.replace(/\sbig-img/, '');
            } else {
                e.currentTarget.className = img + ' big-img';
            }
        },
        /*获取本地聊天记录*/
        // getChatRecord(){
        //     let that = this;
        //     let list = window.localStorage.getItem("NWImChatList") ? JSON.parse( window.localStorage.getItem("NWImChatList") ) : [];
        //     if(list.length > 0){
        //         for(let value in list){
        //             if(list[value] && list[value].storeId == that.storeId){
        //                 that.chatMsgList.push(...list[value].list )
        //             }
        //         }
        //     }
        // },
        /*获取云信的聊天室记录*/
        getImChatRecord () {
            let that = this;
            // if(!that.chatGroupId){
            //     return
            // }
            this.nim.getHistoryMsgs({
                scene: that.scene,//这里可以p2p也可以team
                to: that.chatGroupId,
                done: getHistoryMsgsDone
            });

            function getHistoryMsgsDone (error, obj) {
                console.log(obj, '聊天室记录');
                obj = obj.msgs;
                that.sessionId = obj[0].sessionId // 清除未读数的聊天Id
                if (Array.isArray(obj) && obj.length > 0) {
                    let tempObj = {};
                    let messageType = 0;
                    let medioUrl = '';
                    let objLength = obj.length;
                    let value;
                    for (let i = objLength - 1; i >= 0; i--) {
                        value = obj[i];
                        switch (value.type) {
                            case 'image':
                                messageType = 1;
                                break;
                            case 'audio':
                                messageType = 2;
                                break;
                            case 'video':
                                messageType = 3;
                                break;
                            case 'text':
                                messageType = 0;
                                break;
                            default:
                                messageType = 0;
                                break;
                        }
                        if (value.type != 0 && value.file && value.file.url) {
                            medioUrl = value.file.url
                        }
                        tempObj = {
                            time: value.time,
                            avatar: that.account == value.from,
                            userheader: that.$store.state.currentUser.photoUrl || '',//用户或者商家的头衔
                            name: that.$store.state.currentUser.userName || '',//用户/客服名字，
                            content: {
                                text: value.text,
                                messageType: messageType,//消息类型（0文本消息 1图片 2语音 3视频 4地理位置 5红包 6转账)
                                mediaUrl: medioUrl,
                            },
                        };

                        // content:msg.text,
                        // messageType:messageType,
                        // medioUrl:medioUrl,
                        // time:msg.time,
                        // isReceive:true,//是否为接收消息
                        if (value.pushContent != "你有一条新消息!" && value.type != "notification") {
                            that.chatMsgList.push(tempObj);
                        }
                    }
                }
            }
        },
        /*存储聊天记录*/
        // saveChatRecord(obj){
        //     let that = this;
        //     let list = window.localStorage.getItem("NWImChatList") ? JSON.parse( window.localStorage.getItem("NWImChatList") ) : [];
        //     if( list.length > 0 ){
        //         let hasRecord = false;
        //         for(let value in list){
        //             if(list[value] && list[value].storeId == that.storeId){
        //                 list[value].list.push(obj);
        //                 /*当聊天记录大于100条时候就删除以前的聊天记录*/
        //                 if(list[value].list.length > 100){
        //                     list[value].list.shift(obj);
        //                 }
        //                 hasRecord = true;
        //             }
        //         }
        //         if(!hasRecord){
        //             let tempObj = {
        //                 storeId:that.storeId,
        //                 storeLogo:that.storeMsg.logo,
        //                 storeName:that.storeMsg.name,
        //                 list:[obj],
        //             }
        //             list.push(tempObj);
        //         }
        //     }else{
        //         let tempObj = {
        //             storeId:that.storeId,
        //             storeLogo:that.storeMsg.logo,
        //             storeName:that.storeMsg.name,
        //             list:[obj],
        //         }
        //         list.push(tempObj);
        //     }
        //     window.localStorage.setItem("NWImChatList",JSON.stringify(list));
        // },
        /*表情切换*/
        tapFace (obj) {
            if (obj == 'face') {
                this.showFace = !this.showFace;
                this.showPics = false;
            } else if (obj == "pic") {
                this.showPics = !this.showPics;
                this.showFace = false;
            }
        },
        /*把表情放入输入框中*/
        addFace (e, value) {
            let that = this;
            let tempObj = `<img faceIcon="${value}" style="width: .25rem;height: .25rem;" class="face-icon" src="${e.currentTarget.src}">`
            this.textArea += tempObj;
            /*获取焦点*/
            $('#msgText').append(tempObj);
            /*TODO 这里如果要做好用户体验的话一定要获取到焦点focus,由于现在获取到的焦点只能值表情之前，所以先放着里*/
            // $('#msgText').focus();
        },
        /*让页面显示最后一条信息*/
        scrollBottom (obj) {
            if (this.$route.path.indexOf('/im/chat') > -1) {
                let scrollDiv = this.$refs.scrllBottom
                scrollDiv.scrollTop = scrollDiv.scrollHeight;
                this.imContentHeight = scrollDiv.scrollHeight;
            }
            // var oscrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
            // var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
            // this.imContentHeight = oscrollHeight;
            // $(window).scrollTop(oscrollHeight);

        },
    },

    components: {
        'v-loading': () => import('../../components/commonComponents/loading/FullScreenLoading'),
        'v-ImVideo': ImVideo
    },

    watch: {
        textArea (val) {
            if (val) {
                this.showSendBtn = true;
                return
            }
            this.showSendBtn = false;
        },
        //监听收到的信息刷新页面展示数据
        'hintList.length': {
            handler (newValue, oldValue) {
                if (newValue !== oldValue && this.hintList && this.chatGroupId == this.hintList[0].to) {
                    this.onMsg(this.hintList[0])
                }
            }
        }
    }
}
</script>

<style scoped lang="scss">
.im-header-title {
    color: #333;
    font-size: 0.16rem;
    font-weight: bold;
}

.im--header-ctitle {
    max-width: 90%;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    padding-right: 0.4rem;
}

.im-header {
    height: 0.5rem;
    text-align: center;
    position: fixed;
    padding: 0 0.1rem;
    top: 0;
    left: 0;
    background-color: #fff;
    width: 100%;
    z-index: 100;
}

.back-icon {
    font-weight: bold;
    font-size: 0.24rem;
    padding: 0 0.05rem;
}

.title-mark {
    color: #fff;
    background-color: #8ba9e8;
    border-radius: 0.25rem;
    font-size: 0.1rem;
    padding: 0 0.05rem;
    display: inline-block;
    height: 0.2rem;
    line-height: 0.2rem;
    font-weight: normal;
    position: absolute;
    right: 0;
    bottom: 0;
    top: 0;
    margin: auto;
}

.chat-time {
    color: #999;
    font-size: 0.12rem;
    text-align: center;
    padding-top: 0.2rem;
}

.chat-content {
    padding-top: 0.5rem;
    background-color: #f7f8fa;
    min-height: 100vh;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

.im-chat-userheader {
    height: 0.4rem;
    width: 0.4rem;
    margin-right: 0.1rem;
    border-radius: 0.25rem;
}

.chat-avatar {
    padding: 0.2rem 0.6rem 0 0.15rem;
}

.msg-text-placeholder {
    position: absolute;
    left: 0.1rem;
    top: 0.1rem;
    bottom: 0;
    margin: auto;
    color: #cccccc;
}

.im-chat-content {
    border-top-right-radius: 10px;
    border-bottom-right-radius: 10px;
    border-bottom-left-radius: 10px;
    padding: 0.14rem;
    background-color: #fff;
    color: #333333;
    display: inline-block;
    font-size: 0.15rem;
    margin-top: 0.08rem;
    line-height: 0.24rem;
    letter-spacing: 0.02rem;

    img,
    video,
    audio {
        max-width: 100%;
    }
}

.star-icon {
    width: 0.15rem;
    margin-right: 0.05rem;
}

.im-chat-name {
    font-size: 0.12rem;
    color: #999;
}

.commont-score-text {
    color: #ccc;
}

.store-leader-icon {
    width: 0.2rem;
    height: 0.2rem;
    object-fit: contain;
}

.store-leader-content {
    background-color: #f7f8fa;
    position: relative;
    z-index: 1;
    padding: 0 0.1rem;
}

.store-leader-line {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
    width: 100%;
    height: 1px;
    background-color: #cccccc;
}

.store-leader-text {
    color: #999;
    padding-left: 0.05rem;
}

.chat-receiver {
    flex-direction: row-reverse;
    flex-wrap: wrap;

    .im-chat-content {
        border-top-right-radius: 0;
        border-top-left-radius: 10px;
        background-color: #8ba9e8;
        max-width: 2.95rem;
        margin-right: 0.15rem;
        color: #fff;
        margin-top: 0.2rem;
    }
}

.send-msg {
    background-color: #8ba9e8;
    color: #fff;
    font-size: 0.12rem;
    border-radius: 0.25rem;
    padding: 0.05rem 0.1rem;
    position: relative;
    z-index: 1030;
}

.im-chat-input-icon {
    height: 0.26rem;
}

.im-chat-input-wicon {
    padding-bottom: 0.1rem;
}

.input-wrap {
    position: fixed;
    width: 3.45rem;
    left: 0;
    right: 0;
    bottom: 0.15rem;
    margin: auto;
    background-color: #fff;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    z-index: 100;
}

.im-chat-textarea {
    width: 100%;
    padding: 0.1rem;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    overflow: scroll;
    overflow-y: scroll;
    overflow-x: hidden;
    -webkit-user-select: text;
    position: relative;
    z-index: 1;
}

.face-box {
    height: 1.8rem;
    overflow: scroll;
    padding: 0.1rem;
}

.photos {
    background-color: #e6ebf5;
}

.face-icon {
    display: inline-block;
    height: 0.3rem;
    width: 0.3rem;
    padding: 0.02rem;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    object-fit: contain;
}

.camera-input {
    opacity: 0;
    width: 0;
    height: 0;
    position: absolute;
    z-index: -1;
    display: none;
}

.photos-wrap {
    color: #999999;
    font-size: 0.14rem;
    width: 0.7rem;
    text-align: center;

    img {
        width: 0.7rem;
    }
}

.big-img {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    background-color: rgba(0, 0, 0, 1);
    width: 100%;
    height: 100%;
    object-fit: contain;
    z-index: 1050;
}

.key-bord {
    height: 1.8rem;
    width: 100%;
}

.video-icon {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: auto;
    width: 30%;
}
.box {
    position: fixed;
    left: 0;
    top: 0;
    overflow-y: auto;
    width: 100%;
    height: 100%;
}
</style>